package directive;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modele.beans.Key;
import modele.dao.KeyDAO;
import modele.form.KeyForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class KeyAction extends GlobalAction {
	private KeyDAO keyDAO;
	
	@Override
	public String executeAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		keyDAO = new KeyDAO(this.conn);
		String type = (String) request.getParameter("type");
		String ac = ACTION_FAIL;

		if (type.equals("Ajouter"))
			ac = AddKey(mapping, form);
		else if (type.equals("Modifier"))
			ac = UpdateKey(mapping, form);
		else if (type.equals("Supprimer"))
			ac = DeleteKey(mapping, form);
		else
			ac = ACTION_SUCCESS;
		
		KeyForm key = (KeyForm) form;
		
		if (ac.equals(ACTION_SUCCESS)) {
			key.setName("");
			key.setDescription("");
			key.setId("");
		}
	
		key.setKeys(GetKeys());
		request.setAttribute("KeyForm", key);
		
		return ac;
	}

	private String AddKey(ActionMapping mapping, ActionForm form) {
		KeyForm key = (KeyForm) form;

		Key k = new Key(key.getName(),
				key.getDescription(), 
				key.getId());
		try {
			keyDAO.AddKey(k);
		} catch (SQLException e) {
			return ACTION_FAIL;
		} catch (ClassNotFoundException e) {
			return ACTION_FAIL;
		}
		return ACTION_SUCCESS;
	}
	
	private String UpdateKey(ActionMapping mapping, ActionForm form) {
		KeyForm key = (KeyForm) form;

		Key k = new Key(key.getName(),
				key.getDescription(), 
				key.getId());
		try {
			keyDAO.UpdateKey(k);
		} catch (SQLException e) {
			return ACTION_FAIL;
		} catch (ClassNotFoundException e) {
			return ACTION_FAIL;
		}
		return ACTION_SUCCESS;
	}
	
	private String DeleteKey(ActionMapping mapping, ActionForm form) {
		KeyForm key = (KeyForm) form;

		Key k = new Key(key.getName(),
				key.getDescription(), 
				key.getId());
		try {
			keyDAO.RemoveKey(k);
		} catch (SQLException e) {
			return ACTION_FAIL;
		} catch (ClassNotFoundException e) {
			return ACTION_FAIL;
		}
		return ACTION_SUCCESS;
	}

	private ArrayList<Key> GetKeys() {
		try {
			return keyDAO.GetKeys();
		} catch (SQLException e) {
			return new ArrayList<Key>();
		} catch (ClassNotFoundException e) {
			return new ArrayList<Key>();
		}
	}
}